package com.ht.WeNas.dao.repo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ht.WeNas.config.data.CacheNameEnum;
import com.ht.WeNas.dao.mapper.FileBucketInfoMapper;
import com.ht.WeNas.data.entity.FbInfo;
import com.ht.WeNas.utils.CacheUtil;
import com.ht.WeNas.utils.MyThreadPool;
import org.springframework.stereotype.Repository;

import java.io.Serializable;

@Repository
public class FileBucketInfoRepo {
    private final CacheUtil cacheUtil;
    private final FileBucketInfoMapper thisMapper;

    public FileBucketInfoRepo(CacheUtil cacheUtil, FileBucketInfoMapper thisMapper) {
        this.cacheUtil = cacheUtil;
        this.thisMapper = thisMapper;
    }

    public void save(FbInfo entity) {
        thisMapper.insert(entity);
    }

    public FbInfo getById(Serializable id) {
        return cacheUtil.cacheRead(
                CacheNameEnum.FB_info,
                id,
                (key) -> thisMapper.selectById(id)
        );
    }
    
    public void updateById(FbInfo fbInfo) {
        try {
            thisMapper.updateById(fbInfo);
        } finally {
            cacheUtil.dropCache(CacheNameEnum.FB_info, fbInfo.getId());
        }
    }

    public Page<FbInfo> page(Page<FbInfo> objectPage, LambdaQueryWrapper<FbInfo> wrapper) {
        Page<FbInfo> page = thisMapper.selectPage(objectPage, wrapper);
        MyThreadPool.execAsync(() -> {
            page.getRecords().forEach(item -> {
                cacheUtil.cache(CacheNameEnum.FB_info, item.getId(), item);
            });
        });
        return page;
    }

    public void removeById(Long id) {
        cacheUtil.dropCache(CacheNameEnum.FB_info, id);
        thisMapper.deleteById(id);
    }
}
